package com.example.zookeeper.lock.util;

import com.example.zookeeper.lock.task.WorkTask;
import io.netty.util.concurrent.DefaultThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @author Vicente
 * @version 1.0
 * @date 2020/3/9 15:00
 */
public class DefaultExecutor {
    private Logger logger = LoggerFactory.getLogger(DefaultExecutor.class);
    private static DefaultExecutor defaultExecutor;
    private static ThreadPoolExecutor pool;
    private static boolean isPoolInit = false;
    private DefaultExecutor(){

    }

    /**
     * 获取任务提交对象
     * @return
     */
    public static DefaultExecutor getInstance(){
        if(defaultExecutor == null){
            synchronized (DefaultExecutor.class){
                if(defaultExecutor == null){
                    defaultExecutor = new DefaultExecutor();
                    if(!isPoolInit || pool.isShutdown()){
                        initThreadPool();
                    }
                }
            }
        }
        return defaultExecutor;
    }

    /**
     * 初始化线程池
     */
    public static void initThreadPool(){
        pool = new ThreadPoolExecutor(
                10,
                20,
                60L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(10),
                new DefaultThreadFactory(Runnable.class),
                new ThreadPoolExecutor.AbortPolicy());
    }

    public void invokeAsync(List<FutureTask<Callable>> workList){
        if(workList.size() != 0){
            for (FutureTask<Callable> task: workList) {
                pool.submit(task);
            }
        }else{
            logger.warn("当前没有待提交任务......");
        }
    }
}
